<template>
  <div class="footer-page">
    <el-form ref="form" :rules="rules" :model="form" label-width="160px">
      <el-form-item label="上级分类:" prop="module_type">
        <el-select v-model="form.module_type" placeholder="请选择上级分类">
          <el-option label="热门推荐" value="1" />
          <el-option label="自定义模块" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="板块名称:" prop="main_title">
        <el-input v-model="form.main_title" />
      </el-form-item>
      <el-form-item label="排序:">
        <el-input-number v-model="form.module_sort" />
      </el-form-item>
    </el-form>
    <div class="page-footer-btns">
      <el-button size="small" @click="resetForm">重置</el-button>
      <el-button size="small" type="primary" @click="submitForm">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addHomeModule, getHomeModuleById } from '@/api/web'
export default {
  // props: ['editId'],
  props: {
    editId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      form: {
        module_type: null,
        main_title: '',
        module_sort: 0
      },
      rules: {
        module_type: [
          { required: true, message: '请选择上级分类', trigger: 'change' }
        ],
        main_title: [
          { required: true, message: '板块名称不能为空', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    if (this.editId) {
      this.$route.meta.title = '编辑板块'
      this.getData()
    } else {
      this.$route.meta.title = '添加板块'
    }
  },
  methods: {
    // 编辑获取信息
    getData() {
      getHomeModuleById(this.editId).then(res => {
        this.form.module_id = res.id
        this.form.main_title = res.main_title
        this.form.module_type = res.module_type + ''
        this.form.module_sort = res.module_sort
      })
    },
    // 表单提交
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          addHomeModule(this.form).then(res => {
            if (!this.editId) {
              // 新增跳转列表页
              this.$router.push({ name: 'webConfigShow' })
            }
          })
        } else {
          this.$message({
            message: '请检查表单错误',
            type: 'error'
          })
          return false
        }
      })
    },
    // 重置
    resetForm() {
      this.$refs['form'].resetFields()
      if (this.editId) {
        this.getData()
      } else {
        this.form = {
          module_type: null,
          main_title: '',
          module_sort: 0
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
